package org.zetaframework.satoken.interceptor;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.same.SaSameUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.zetaframework.core.utils.ContextUtil;

/**
 * Same-token 校验拦截器
 *
 * 专门用于校验微服务间的 Same-token，不进行登录校验
 * @author gcc
 */
public class SameTokenInterceptor implements HandlerInterceptor {

    /**
     * 每次请求之前触发的方法
     *
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @param handler Object
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 校验Same-token 说明：可以没有token，但一定要有same-token
        String token = SaHolder.getRequest().getHeader(SaSameUtil.SAME_TOKEN);
        SaSameUtil.checkToken(token);
        ContextUtil.setSameToken(token);

        return true;
    }
}
